//
//  ADController.swift
//  zhonglb_iOS
//
//  Created by lxm on 2022/3/10.
//

import UIKit
import RxSwift

class ADController: ZMViewController {

    //MARK:--------------------属性--------------------
    var resource = ""
    // 记时器
    private let timer = Observable<Int>.timer(.seconds(0), period: .seconds(1), scheduler: MainScheduler.instance)
    
    var adTime = 20
    
    var timeDisposeBag = DisposeBag()
    var onStart : (()->())?
    // 观看完成回调
    var onSuccessClose : (()->())?
    // 手动关闭回调
    var onHandClose : (()->())?
    
    var isVideo = false
    //MARK:--------------------UI控件--------------------
    
    @IBOutlet weak var img: UIImageView!
    
    @IBOutlet weak var imgH: NSLayoutConstraint!
    
    @IBOutlet weak var closebtn: UIButton!
    
    @IBOutlet weak var imgTop: NSLayoutConstraint!
    
    lazy var palyerView = PlayerView()
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
    }
    //MARK:--------------------UI--------------------
    func setUI() {
        isVideo = resource.hasSuffix(".mp4")
        if isVideo {
            // 视频
            setVideo()
        } else {
            setImg()
        }
    }
    
    // 视频广告
    func setVideo() {
        view.insertSubview(palyerView, belowSubview: closebtn)
        palyerView.snp.makeConstraints { make in
            make.edges.equalTo(view.safeAreaLayoutGuide)
        }
        palyerView.videoType = .advertisement
        let avpsource = AVPUrlSource()
        avpsource.url(with: resource)
        palyerView.isUserInteractionEnabled = false
        palyerView.play(source: avpsource)
        
        palyerView.playStatus.subscribe(onNext:{ [unowned self] resp in
            if resp == AVPStatusPrepared {
                // 视频广告准备完成，开始计时
                self.startVideoTimer()
            } else if resp == AVPStatusCompletion {
                // 播放完成
                self.successClose()
            }
        }).disposed(by: disposeBag)
    }
    
    func startVideoTimer() {
        timer.subscribe(onNext:{ [unowned self] resp in
            if self.adTime > 0 {
                self.adTime -= 1
            } else {
                self.timeDisposeBag = DisposeBag()
                self.closebtn.setTitle("关闭", for: .normal)
                return
            }
            self.closebtn.setTitle("剩余\(adTime)s（关闭）", for: .normal)
        }).disposed(by: timeDisposeBag)
    }
    
    // 图片广告
    func setImg() {
        img.kf.setImage(with: URL.init(string: resource), placeholder: UIImage.init(named:"def_img"), options: nil) { r in
            switch r {
                case .success(let img):
                print(img.image.size, "size is this")
                let height = SCREEN_W / img.image.size.width * img.image.size.height
                if height < SCREEN_H {
                    // 让图片剧中线显示
                    self.imgTop.constant = (SCREEN_H - height) / 2
                }
                self.imgH.constant = height
                break
                case.failure(let e):
                break
            }
        }
        
        timer.subscribe(onNext:{ [unowned self] resp in
            if self.adTime > 0 {
                self.adTime -= 1
            } else {
                self.timeDisposeBag = DisposeBag()
                self.successClose()
            }
            self.closebtn.setTitle("剩余\(adTime)s（关闭）", for: .normal)
        }).disposed(by: timeDisposeBag)
    }
    
    
    
    func addConstraints() {
        
    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        
    }
    
    func successClose() {
        dismiss(animated: true, completion: onSuccessClose)
    }

    @IBAction func onClose(_ sender: Any) {
        if self.adTime > 0 {
            dismiss(animated: true, completion: onHandClose)
        } else {
            dismiss(animated: true, completion: onSuccessClose)
        }
    }
    //MARK:--------------------delegate--------------------

}
